package com.education.platform.filter;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * CORS跨域过滤器
 * 
 * @author education-platform
 * @since 2024-10-07
 */
@Component
@Order(1) // 确保在其他过滤器之前执行
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // 获取请求来源
        String origin = httpRequest.getHeader("Origin");
        
        // 设置CORS响应头 - 只有当有Origin头时才设置
        if (origin != null && isAllowedOrigin(origin)) {
            httpResponse.setHeader("Access-Control-Allow-Origin", origin);
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        }
        
        httpResponse.setHeader("Access-Control-Allow-Methods", 
                "GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH");
        httpResponse.setHeader("Access-Control-Allow-Headers", 
                "Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Pragma");
        httpResponse.setHeader("Access-Control-Expose-Headers", 
                "Authorization, Content-Type, X-Requested-With, Accept, Origin, Access-Control-Request-Method, Access-Control-Request-Headers");
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        
        // 处理OPTIONS预检请求
        if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        
        // 继续执行后续过滤器
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化逻辑
    }

    @Override
    public void destroy() {
        // 清理逻辑
    }
    
    /**
     * 检查是否是允许的源
     */
    private boolean isAllowedOrigin(String origin) {
        if (origin == null) {
            return false;
        }
        
        // 允许本地开发环境
        return origin.startsWith("http://localhost") ||
               origin.startsWith("http://127.0.0.1") ||
               origin.startsWith("http://192.168.") ||
               origin.startsWith("http://10.") ||
               origin.startsWith("https://localhost") ||
               origin.startsWith("https://127.0.0.1");
    }
}
